/**
 * Created by jianglinjie on Wed Sep 27 2017
 * @flow
 */
'use strict';

import type { ILoginStrategy } from './ILoginStrategy';
import type { LoginParam } from '../types';
import type { UserInfo } from '../types'
import { createError } from '../../../utils/ErrorUtils';
import User from '../../../db/models/User';
import { ErrorCode } from '../../../constants';
import { isPhone } from '../../../utils/CheckUtils';
import { getCaptchaRedisKey } from '../../../utils/CaptchaUtils';
import { CaptchaBusiness } from '../../../constants';
import redis from '../../../redis';
import { logger } from '../../../utils/LoggerUtils';

export default class PhoneCaptchaStrategy implements ILoginStrategy {
  async login(param: LoginParam): Promise<UserInfo> {
    if (!isPhone(param.phone)) {
      throw createError(401, '手机号不合法', ErrorCode.PHONE_INVALID);
    }

    if (!param.captcha) {
      throw createError(401, '缺少验证码', ErrorCode.REQUIRE_CAPTCHA);          
    }

    let redisKey = getCaptchaRedisKey(param.phone, CaptchaBusiness.LOGIN);
    let captcha = await redis.getAsync(redisKey);
    if (captcha !== param.captcha) {
      throw createError(401, '验证码已失效，请重新获取', ErrorCode.CAPTCHA_INVALID);
    }

    //登录成功删除验证码
    redis.delAsync(redisKey).catch(delErr => {
      logger.error('redis delete redisKey %s error', redisKey, delErr);
    });

    let user = await User.findOne({ phone: param.phone }).exec();

    if (user) {
      return user.toUserInfo();
    } else {
      throw createError(401, '手机号未注册', ErrorCode.PHONE_NOT_EXIST);
    }
  }
}